package edu.nepu.flink.api.windowjoin;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.JoinFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @Date 2024/3/1 17:07
 * @Created by chenshuaijun
 */
public class JoinWindow {


    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<WaterSensor> source1 = env.fromElements(
                new WaterSensor("s1", 1L, 1),
                new WaterSensor("s1", 2L, 11),
                new WaterSensor("s3", 2L, 1),
                new WaterSensor("s4", 2L, 1)
        );
        DataStreamSource<WaterSensor> source2 = env.fromElements(
                new WaterSensor("s1", 3L, 4),
                new WaterSensor("s1", 4L, 5),
                new WaterSensor("s3", 5L, 6),
                new WaterSensor("s4", 12L, 1)
        );

        SingleOutputStreamOperator<WaterSensor> watermarksSource1 = source1.assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forMonotonousTimestamps().withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
            @Override
            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                return element.getTs() * 1000;
            }
        }));
        SingleOutputStreamOperator<WaterSensor> watermarksSource2 = source2.assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forMonotonousTimestamps().withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
            @Override
            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                return element.getTs() * 1000;
            }
        }));

        /**
         * window join的特点是处于一个窗口内的数据才会进行join
         * 对于join不上的数据是不会进行输出的
         */
        watermarksSource1.join(watermarksSource2)
                .where(WaterSensor::getId)
                .equalTo(WaterSensor::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .apply(new JoinFunction<WaterSensor, WaterSensor, String>() {
                    @Override
                    public String join(WaterSensor first, WaterSensor second) throws Exception {
                        return "join result: " + first + "--->" + second;
                    }
                }).print();

        env.execute();
    }
}
